import { ref, h, onMounted } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useRoute } from "vue-router";
import { useRouterNavigation } from "@/router/utils";
import editForm from "../../form/index.vue";
import type { FormItemProps } from "../../utils/types";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";

import {
  supplierUpdate,
  getSupplierDetail
} from "@/api/basicArchives/supplierManagement";

export function useStoreDetil() {
  // 返回上一页
  const { go } = useRouterNavigation();
  function goBack(n) {
    go(n);
  }
  const formRef = ref();

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}供应商`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          supplierName: row?.supplierName ?? undefined,
          contacts: row?.contacts ?? undefined,
          contact: row?.contact ?? undefined,
          type: row?.type ?? undefined,
          supplierCode: row?.supplierCode ?? undefined,
          website: row?.website ?? undefined,
          address: row?.address ?? undefined,
          labelIdList: row?.labelIdList ?? [],
          des: row?.des ?? undefined
        }
      },
      width: "30%",
      fullscreenIcon: true,
      closeOnClickModal: false,
      sureBtnLoading: true,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const { code } = await supplierUpdate(curData);
              if (code == 200) {
                chores();
                getDetailInfo();
              }
            }
          }
        });
      }
    });
  }

  const storeId = ref<any>("");
  const storeInfo = ref<any>({});

  async function getDetailInfo() {
    const res = await getSupplierDetail({ id: storeId.value });
    storeInfo.value = res.data;
  }

  onMounted(async () => {
    const { query } = useRoute();
    storeId.value = query.id;
    if (query.id) getDetailInfo();
  });

  return {
    storeInfo,
    useRenderIcon,
    goBack,
    openDialog
  };
}
